package com.dk.config;

import com.dk.shiro.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class UserShiroConfig {

    /**
     * 创建ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager());

        // 添加shiro内置过滤器
        Map<String,String> filterMap = new LinkedHashMap<>();
//        filterMap.put("/seller/toLogin","anon");
//        filterMap.put("/seller/toRegister","anon");
//        filterMap.put("/seller/sellerLogin","anon");
//        filterMap.put("/seller/sellerRegister","anon");
//        filterMap.put("/css/*","anon");
//        filterMap.put("/img/*","anon");
//        filterMap.put("/plugins/*","anon");
//        filterMap.put("/add","perms[add]");
//        filterMap.put("/update","perms[update]");
//        filterMap.put("/role/toAdd","perms[role:add]");
        filterMap.put("/toHomeIndex","authc");
        filterMap.put("/**","anon");
        // 修改跳转的登录页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 创建DefaultWebSecurityManager
     * @return
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // 关联realm
        defaultWebSecurityManager.setRealm(getSellerRealm());
        return defaultWebSecurityManager;
    }

    /**
     * 创建getUserRealm
     * @return
     */
    @Bean
    public UserRealm getSellerRealm() {
        UserRealm userRealm = new UserRealm();
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return userRealm;
    }

    // 配置加密方式
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 指定加密方式
        credentialsMatcher.setHashAlgorithmName("MD5");
        // 加密次数
        credentialsMatcher.setHashIterations(3);
        // 编码
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }
}
